﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.ContextManagement
{
    /// <summary>
    /// Updates a <see cref="Context"/>'s <see cref="Context.DeclarationProperty"/>
    /// when it's <see cref="Context.PropertyPathProperty"/> changes.
    /// </summary>
    public class DeclarationManager
    {
        Context Target { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="DeclarationManager"/> class.
        /// </summary>
        /// <param name="target">The target.</param>
        public DeclarationManager(Context target)
        {
            this.Target = target;
            target.DependencyPropertyChanged += target_DependencyPropertyChanged;
        }

        void target_DependencyPropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == Context.PropertyPathProperty)
            {
                if (string.IsNullOrEmpty(e.NewValue as string) && !string.IsNullOrEmpty(e.OldValue as string))
                {
                    Context.SetDeclaration(Target, null);
                }
                else
                {
                    var declaration = new Declaration() { Path = Target.PropertyPath };
                    Context.SetDeclaration(Target, declaration);
                }
            }
        }
    }
}
